package com.psy.counseling.controller;


import cn.hutool.core.util.StrUtil;
import com.psy.counseling.entity.User;
import com.psy.counseling.entity.VerifyCode;
import com.psy.counseling.service.IVerifyCodeGen;
import com.psy.counseling.service.LoginLogService;
import com.psy.counseling.service.ReportService;
import com.psy.counseling.service.UserService;
import com.psy.counseling.service.impl.SimpleCharVerifyCodeGenImpl;
import com.psy.counseling.service.impl.UserServiceImpl;
import com.psy.counseling.utils.CommonUtils;
import com.psy.counseling.utils.ExportExcel;
import com.psy.counseling.utils.Result;
import com.psy.counseling.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.thymeleaf.util.DateUtils;

import javax.activation.MimetypesFileTypeMap;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 梁学儒
 * @since 2022-05-31
 */
@CrossOrigin //允许跨域请求
@RestController
@RequestMapping("/api/user")
@Slf4j
public class UserController {

    @Resource
    private UserServiceImpl userService;

    @Resource
    private ReportService reportService;

    @Resource
    private LoginLogService loginLogService;

    @PostMapping("/login")
    public ResultVo login(@RequestBody LoginVo loginVo, HttpSession session) {
        loginLogService.log(loginVo.getUsername(), StrUtil.format("用户 {} 登录系统", loginVo.getUsername()));
        return userService.login(loginVo, session);

    }

    @PostMapping("/register")
    public ResultVo register(@Valid @RequestBody RegisterVo registerVo) {
        loginLogService.log(registerVo.getUsername(), StrUtil.format("用户 {} 注册账号成功", registerVo.getUsername()));
        return userService.register(registerVo);
    }

    //    @ApiOperation(value = "验证码")
    @GetMapping("/verifyCode")
    public void verifyCode(HttpServletRequest request, HttpServletResponse response) {
        IVerifyCodeGen iVerifyCodeGen = new SimpleCharVerifyCodeGenImpl();
        try {
            //设置长宽
            VerifyCode verifyCode = iVerifyCodeGen.generate(80, 28);
            String code = verifyCode.getCode();
//            LOGGER.info(code);
            log.info(code);
            //将VerifyCode绑定session
            request.getSession().setAttribute("VerifyCode", code);
            //设置响应头,输出的内容为图片
            response.setHeader("Pragma", "no-cache");
            //设置响应头,不要缓存此内容
            response.setHeader("Cache-Control", "no-cache");
            //在代理服务器端防止缓冲
            response.setDateHeader("Expires", 0);
            //设置响应内容类型
            response.setContentType("image/jpeg");
            response.getOutputStream().write(verifyCode.getImgBytes());
            response.getOutputStream().flush();
        } catch (IOException e) {
//            LOGGER.info("", e);
            log.info("", e);
        }
    }

    @PostMapping("/updatePassword")
    public ResultVo updatePwd(@RequestBody UpdatePasswordVo updatePasswordVo) {
        return userService.updatePassword(updatePasswordVo);
    }

//    /**
//     * 用户上传头像
//     * @param file
//     * @return
//     */
//    @PostMapping("/photo")
//    public Result photo(@RequestParam("file") MultipartFile file) {
//        return userService.uploadHeadPhoto(file);
//    }

    @PostMapping("/addUser")
    public ResultVo addUser(@Valid User user,Long roleId) {
        loginLogService.log(StrUtil.format("新增用户：{} ", user.getUsername()),user);
        return userService.addUser(user,roleId);
    }

    @DeleteMapping("/deleteUser")
    public ResultVo addUser(@RequestBody DeleteVO deleteVO) {
        return userService.deleteUser(deleteVO);
    }

    @GetMapping("/getUser")
    public ResultVo getUser(User user, PageVO page,Long roleId) {
        return userService.listUsers(user,page,roleId);
    }

    @PostMapping("/updateUser")
    public ResultVo updateUser(@RequestBody User user) {
        System.out.println(user);
        loginLogService.log(StrUtil.format("更新用户：{} ", user.getUsername()),user);
        return userService.updateUser(user);
    }

    @PostMapping("/updateUserRole")
    public ResultVo updateUserRole(@RequestBody UserRoleVo userRoleVo) {
        return userService.updateUserRole(userRoleVo);
    }

    @GetMapping("/reportExport/{excelTitle}")
    public Object prodTest(HttpServletResponse response, @PathVariable("excelTitle") String excelTitle) throws IOException {
        // 创建导出文件名称 当前日期+前台传递过来的标题名（excelTitle）
//        String fileName = DateUtils.format(new Date(),"yyyyMMddHHmmss") +"-"+excelTitle+".xls";
        String fileName = excelTitle + ".xls";
        // 设置返回的消息头和返回值类型 并设置编码 不设置编码文件名为中文的话 不会显示
        // 当设置成如下返回值时，浏览器才会执行下载文件动作
        response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
        response.setContentType("APPLICATION/OCTET-STREAM;charset=UTF-8");
        // 创建输出流，调用service中exportTest方法，参数：输出流 标题名
        reportService.exportTest(response.getOutputStream(), excelTitle);
        return null;
    }

    @PostMapping("/importUsers")
    public Result<?> importUsers(@RequestBody MultipartFile file) throws IOException {
        ArrayList<Integer> errorList = userService.importUsers(file);
        errorList.forEach(System.out::println);
        return Result.success(errorList);
    }

    /**
     * 下载导入用户模板
     * @param response
     * @param filePath
     * @throws Exception
     */
    @GetMapping("/downloadExcelTemplate")
    public void downloadExcelTemplate(HttpServletResponse response,@Value("${excel.template}")String filePath) throws Exception {
        CommonUtils.download(response, filePath );
    }

    @GetMapping("/getFaculty")
    public ResultVo getFaculty() {
      return userService.getFaculty();
    }

//    /**
//     * 校验激活码
//     *
//     * @param code
//     * @return
//     */
//    @GetMapping(value = "/checkCode/{code}")
//    public ResultVo checkCode(@PathVariable("code") String code) {
//        return userService.activation(code);
//    }
}

